/*
 * DesignAssignment2.c
 *
 * Created: 2/25/2014 9:12:26 PM
 *  Author: Vincent
 */ 


#include <avr/io.h>
#include <avr/interrupt.h>
#define F_CPU 1000000UL									// 1 MHz
                                                        //#define F_CPU 14.7456E6
#include <util/delay.h>

volatile int ctrInt = 0;

void delay_waveform();
int main(void)
{
        EICRA = (1<<ISC01);    //enable external interrupt ISC01 on falling edge
        EIMSK = (1<<INT0);     //enable external Mask INT0
        sei ();                //enable interrupts     
        int bCounter = 0;
        DDRD |= 0b1011;        //set DDRD.3(Interrupt Flag), DDRD.0(DelayWaveform) and DDRD.1(Status) as output
        DDRB |= 0xFF;          //make DDRB output

        while(1){       
                delay_waveform();
                if (PORTD & (1<<PD0))					//if PD0 is set
                {
                        delay_waveform();
                        PORTB = ++bCounter;             //this 8bit counter will toggle for PD0 falling edge
                        if(bCounter==255)               //counter will reset once it reaches 255
                                bCounter = 0;
						if((bCounter%20)==0)            //toggle PD1 for every 10 falling edge of counter
                                PORTD ^= 1<<PD1;
                }

        }
}


ISR (INT0_vect) //ISR for external interrupt 0
{
	++ctrInt;
	if (ctrInt == 2)
	{
		PORTD |= (1<<PD3); //set PORTD.3	
		ctrInt = 0;
	}
}
void delay_waveform()
{
        _delay_ms(250.0);
        PORTD ^= 1<<PD0;
}

//8bit counter will be on PORTB
//PD3 would be the interrupt flag, 10th LED
//PD0 will be our waveform
//PD1 will be our status register, 9th LED
//PORTB will be our counter
//PD2/INT0 will be connected to the status register, PD1